﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.SkiaSharpView.WPF;
using SkiaSharp;

namespace TestWpfLiveCharts2.Controls
{
    /// <summary>
    /// 基于图表控件，附加一些额外的功能
    /// </summary>
    public class MyCartesianChart : CartesianChart
    {
        private bool isDragging = false;
        private SelectRectangleSectionRack? rectSelectionRack = null;

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            isDragging = true;

            // 计算点击初始位置
            var controlPosition = e.GetPosition(this);
            var dataPosition = ScalePixelsToData(new LvcPointD(controlPosition.X, controlPosition.Y));

            // 使用新的选择矩形
            rectSelectionRack?.Dispose();
            rectSelectionRack = new SelectRectangleSectionRack(this, dataPosition.X, dataPosition.Y);

            base.OnMouseLeftButtonDown(e);
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (!isDragging) return;

            if (rectSelectionRack is SelectRectangleSectionRack sr)
            {
                var controlPosition = e.GetPosition(this);
                var dataPosition = ScalePixelsToData(new LvcPointD(controlPosition.X, controlPosition.Y));
                sr.UpdateRect(dataPosition.X, dataPosition.Y);
            }

            base.OnMouseMove(e);
        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {
            isDragging = false;

            if (rectSelectionRack is SelectRectangleSectionRack sr)
            {
                if (!sr.IsValidRect)
                {
                    // 点击形成的0大小矩形，不计入选区。
                    rectSelectionRack.Dispose();
                    rectSelectionRack = null;
                }
            }
            base.OnMouseLeftButtonUp(e);
        }
    }
}